package cn.lbwfree.web.controller;

import cn.lbwfree.web.entity.Book;
import cn.lbwfree.web.entity.Borrow;
import cn.lbwfree.web.entity.Reader;
import cn.lbwfree.web.service.BookService;
import cn.lbwfree.web.service.impl.BookServiceImpl;
import org.omg.Messaging.SYNC_WITH_TRANSPORT;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "BookServlet", urlPatterns = "/book")
public class BookServlet extends HttpServlet {
    private BookService bookService = new BookServiceImpl();

    /**
     * 图书的数据
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        //没有method就默认查询结果
        if (method == null)
        {
            method = "findAll";
        }
        System.out.println("BookServlet success");
        HttpSession session = request.getSession();
        Reader reader = (Reader) session.getAttribute("reader");
        switch (method){
            case "findAll":
                String pageStr ;
                pageStr= request.getParameter("page");
                Integer page = Integer.valueOf(pageStr);
                List<Book> list = bookService.findAll(page);
                request.setAttribute("list", list);
                request.setAttribute("dataPrePage", 6);
                request.setAttribute("currentPage", page);
                request.setAttribute("pages", bookService.getPages());
                request.getRequestDispatcher("index.jsp").forward(request, response);
                break;
                // 添加借书请求
            case "addBorrow":
                String bookidStr = request.getParameter("bookid");
                Integer bookid = Integer.valueOf(bookidStr);
                bookService.addBorrow(bookid, reader.getId());
                response.sendRedirect("/book?method=findAllBorrow&page=1");
                break;
            case "findAllBorrow":
                pageStr = request.getParameter("page");
                page = Integer.valueOf(pageStr);
                // 借书记录
                List<Borrow> borrows = bookService.findAllBorrowByReaderId(reader.getId(), page);
                request.setAttribute("list", borrows);
                request.setAttribute("dataPrePage", 6);
                request.setAttribute("currentPage", page);
                request.setAttribute("pages", bookService.getBorrowPages(reader.getId()));
                request.getRequestDispatcher("borrow.jsp").forward(request, response);
                break;
        }



    }
}
